package com.pay.controller;

import com.alipay.api.internal.util.*;
import com.pay.error.ErrorCode;
import com.pay.model.App;
import com.pay.model.Order;
import com.pay.request.PayType;
import com.pay.request.SignType;
import com.pay.request.UnifiedOrder;
import com.pay.response.BaseResult;
import com.pay.response.OrderResult;
import com.pay.service.PayService;
import com.pay.utils.DateUtil;
import com.pay.utils.MathUtil;
import com.pay.web.utils.*;
import com.pay.web.utils.WebUtils;
import com.pay.web.utils.XmlUtils;
import com.pay.wxpay.WXPayUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.Map;
import java.util.HashMap;
import java.util.Date;
import java.io.*;

import com.pay.request.OrderStatus;
import com.pay.web.utils.AlipayUtils;
/**
 * Created by chenweiyi on 2018/1/30.
 */
@Controller
@RequestMapping(value = "pay")
public class PayController {
    /**
     *
     */
    private PrintWriter writer;

    @Autowired
    private PayService payService;

    Logger logger = LoggerFactory.getLogger(PayController.class);

    /**
     * 下单接口
     * 传递XML格式
     * @param request
     * @param response
     */
    @RequestMapping(value = "unifiedOrder",method = RequestMethod.POST)
    public void unifiedOrder(HttpServletRequest request , HttpServletResponse response){
        try{

            String  contentType = request.getContentType().toUpperCase();
            if(contentType.contains("TEXT/XML") || contentType.contains("APPLICATION/JSON")){
                InputStream is = request.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                String line = null;
                StringBuffer content = new StringBuffer();
                while((line = reader.readLine()) != null){
                    content.append(line);
                }
                if(contentType.contains("TEXT/XML") ){
                    Map<String,Object> result = XmlUtils.xmlToMap(content.toString());
                    UnifiedOrder unifiedOrder = WebUtils.mapToObject(result, UnifiedOrder.class);
                    unifiedOrder(unifiedOrder,response);
                }
                else{
                    UnifiedOrder result = GsonUtils.fromJson(content.toString(),UnifiedOrder.class);
                    unifiedOrder(result,response);
                }

            }else{
                Map<String,Object> result = WebUtils.getRequestParameterMap(request);
                UnifiedOrder unifiedOrder = WebUtils.mapToObject(result, UnifiedOrder.class);
                unifiedOrder(unifiedOrder,response);
            }

        }catch(Exception e){
            Map<String,Object> result = ResultUtils.parseFailure(ErrorCode.FAIL_TO_CREATE_ORDER.toString(),ErrorCode.FAIL_TO_CREATE_ORDER.getDescription());
            writeJsonResponse(result,response);
        }

    }

    /**
     * 校验订单
     * @param unifiedOrder
     * @return
     */
    private Map<String,Object> verifyUnifiedOrder(UnifiedOrder unifiedOrder){
        Map<String,Object> result = null;
        if(unifiedOrder != null){

            String appId = unifiedOrder.getAppId();
            if(appId == null || appId.trim().isEmpty()){
                result = ResultUtils.parseFailure(ErrorCode.EMPTY_APP_ID.toString(),ErrorCode.EMPTY_APP_ID.getDescription());
                return result;
            }
            App app = payService.findAppByAppid(appId);

            if(app == null){
                result = ResultUtils.parseFailure(ErrorCode.ERROR_APP_ID.toString(),ErrorCode.ERROR_APP_ID.getDescription());
                return result;
            }

            Integer mchId =  app.getMchId();
            if(mchId == null){
                result = ResultUtils.parseFailure(ErrorCode.ERROR_MCH_ID.toString(),ErrorCode.ERROR_MCH_ID.getDescription());
                return result;
            }
            String status = app.getUserStatus();

            if(status == null ||  status.equals("2")){
                result = ResultUtils.parseFailure(ErrorCode.FREEZE_MCH_ID.toString(),ErrorCode.FREEZE_MCH_ID.getDescription());
                return result;
            }

            String outTradeNo  = unifiedOrder.getOutTradeNo();

            if(outTradeNo == null || outTradeNo.trim().isEmpty()){
                result = ResultUtils.parseFailure(ErrorCode.EMPTY_OUT_TRADE_NO.toString(),ErrorCode.EMPTY_OUT_TRADE_NO.getDescription());
                return result;
            }

            Order order = payService.findOrderByOrderNo(outTradeNo);
            if(order != null){
                result = ResultUtils.parseFailure(ErrorCode.DUPLICATE_OUT_TRADE_NO.toString(),ErrorCode.DUPLICATE_OUT_TRADE_NO.getDescription());
                return result;
            }

            String detail  = unifiedOrder.getDetail();

            if(detail == null || detail.trim().isEmpty()){
                result = ResultUtils.parseFailure(ErrorCode.EMPTY_DETAIL.toString(),ErrorCode.EMPTY_DETAIL.getDescription());
                return result;
            }
            String totalFee = unifiedOrder.getTotalFee();
            Float price = 0.01f;
            if(totalFee == null || totalFee.trim().isEmpty()){
                result = ResultUtils.parseFailure(ErrorCode.EMPTY_TOTAL_FEE.toString(),ErrorCode.EMPTY_TOTAL_FEE.getDescription());
                return result;
            }

            /**
             * 金额以分为单位，整型
             */
            if(totalFee == null || !totalFee.matches("^\\d+$")){
                result = ResultUtils.parseFailure(ErrorCode.ERROR_TOTAL_FEE.toString(),ErrorCode.ERROR_TOTAL_FEE.getDescription());
                return result;
            }else{

                Integer fee = Integer.parseInt(totalFee);
                if(fee == 0){
                    result = ResultUtils.parseFailure(ErrorCode.ERROR_TOTAL_FEE.toString(),ErrorCode.ERROR_TOTAL_FEE.getDescription());
                    return result;
                }
                price = MathUtil.roundScale(fee * 1.0 / 100,2).floatValue();

            }



            String returnUrl = unifiedOrder.getReturnUrl();
            if(returnUrl == null || returnUrl.trim().isEmpty()){
                result = ResultUtils.parseFailure(ErrorCode.EMPTY_RETURN_URL.toString(),ErrorCode.EMPTY_RETURN_URL.getDescription());
                return result;
            }

            String notifyUrl = unifiedOrder.getNotifyUrl();

            if(notifyUrl == null || notifyUrl.trim().isEmpty()){
                result = ResultUtils.parseFailure(ErrorCode.EMPTY_NOTIFY_URL.toString(),ErrorCode.EMPTY_NOTIFY_URL.getDescription());
                return result;
            }

            String appSecret = app.getSecretKey();

            String signature = WebUtils.signature(unifiedOrder,appSecret, SignType.md5);

            if(signature == null || !signature.equals(unifiedOrder.getSignature())){
                result = ResultUtils.parseFailure(ErrorCode.SIGNATURE_ERROR.toString(),ErrorCode.SIGNATURE_ERROR.getDescription());
                return result;
            }

            Order save = new Order();
            save.setAppId(app.getId());
            save.setUuid(Constants.generateUUID());
            save.setCallbackUrl(notifyUrl);
            save.setReturnUrl(returnUrl);
            save.setOrderNo(outTradeNo);
            save.setForUserId(app.getUserId());
            save.setStatus(OrderStatus.WAITING.getStatus());
            save.setPrice(price);
            save.setBeginTime(DateUtil.format(new Date(),DateUtil.YYYY_MM_DD$HH_mm_ss$SSS));
            save.setPayUserInfo(unifiedOrder.getAttach());
            save.setCommodityInfo(unifiedOrder.getDetail());
            try{
                int num = payService.insertOrder(save);
                if(num == 0){
                    result = ResultUtils.parseFailure(ErrorCode.ORDER_NOT_CREATED.toString(),ErrorCode.ORDER_NOT_CREATED.getDescription());
                    return result;
                }else{
                    OrderResult baseResult = new OrderResult();
                    baseResult.setAppId(appId);
                    baseResult.setAttach(unifiedOrder.getAttach());
                    baseResult.setMchId(String.valueOf(mchId));
                    baseResult.setOutTradeNo(outTradeNo);
                    baseResult.setTradeStatus("WAITING");
                    baseResult.setCode(ErrorCode.SUCCESS.toString());
                    baseResult.setDescription(ErrorCode.SUCCESS.getDescription());
                    StringBuffer buffer = new StringBuffer();
                      buffer.append("?orderNo=")
                            .append(outTradeNo)
                            .append("&price=")
                            .append(price)
                            .append("&title=")
                            .append(detail);
                    baseResult.setPayUrl(Constants.PAY_URL +  WebUtils.encodeURI(buffer.toString()));
                    baseResult.setSignature(WebUtils.signature(baseResult,appSecret,SignType.md5));
                    result = ResultUtils.parseSuccess(baseResult);
                    return result;
                }

            }catch(Exception e){
                logger.error("下单失败:{}",e.getMessage());
                e.printStackTrace();
                result = ResultUtils.parseFailure(ErrorCode.FAIL_TO_CREATE_ORDER.toString(),ErrorCode.FAIL_TO_CREATE_ORDER.getDescription());
                return result;
            }

        }else{
            result = ResultUtils.parseFailure(ErrorCode.FAIL_TO_CREATE_ORDER.toString(),ErrorCode.FAIL_TO_CREATE_ORDER.getDescription());
            return result;
        }
    }



    /**
     * 写json响应
     * @param object
     * @param response
     */
    private void writeJsonResponse(Object object,HttpServletResponse response){
        if(!response.isCommitted()){
            response.setContentType("application/json;charset=utf-8");
            response.setCharacterEncoding("utf-8");
            try {
                String json = GsonUtils.toJson(object);
                OutputStream os = response.getOutputStream();
                os.write(json.getBytes("UTF-8"));
                os.flush();
                os.close();
            }catch(Exception e){
                logger.error("write response error:{}",e.getMessage());
                e.printStackTrace();
            }
        }

    }

    /**
     * 下单
     * @param unifiedOrder
     * @param response
     */
    private  void unifiedOrder(UnifiedOrder unifiedOrder, HttpServletResponse response){
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        Map<String,Object> result = verifyUnifiedOrder(unifiedOrder);
        writeJsonResponse(result,response);
    }




    /**
     * 调用微信或支付宝，创建订单
     * @param request
     * @param response
     */
    @RequestMapping(value = "pay",method = RequestMethod.POST)
    public void pay(HttpServletRequest request,HttpServletResponse response){
        String payType = request.getParameter("payType");
        String scheme = request.getScheme();
        boolean secure =  request.isSecure();
        if(secure ){
            scheme = "https";
        }
        int port = request.getServerPort();
        String url = scheme + "://" + request.getServerName() +(port != 80? ":" + request.getServerPort() : "") + request.getRequestURI();
        url = url.substring(0,url.lastIndexOf("/") + 1);
        Map<String,Object> result;
        if(!PayType.isTypeIn(payType)) {
            //支付方式不支持
            result = ResultUtils.parseFailure(ErrorCode.PAYTYPE_NOT_SUPPORTED.toString(), ErrorCode.PAYTYPE_NOT_SUPPORTED.getDescription());
            writeJsonResponse(result,response);
            return;
        }
        String outTradeNo = request.getParameter("outTradeNo");
        Order order = payService.findOrderByOrderNo(outTradeNo);
        if(order == null){
            //订单不存在
            result = ResultUtils.parseFailure(ErrorCode.OUT_TRADE_NO_NOT_EXIST.toString(), ErrorCode.OUT_TRADE_NO_NOT_EXIST.getDescription());
            writeJsonResponse(result,response);
            return;
        }
        if(!OrderStatus.WAITING.getStatus().equals(order.getStatus())){
            //订单不处于等待支付状态
            result = ResultUtils.parseFailure(ErrorCode.NO_WAITING_STATUS.toString(), ErrorCode.NO_WAITING_STATUS.getDescription());
            writeJsonResponse(result,response);
            return;
        }

        if(PayType.ALIPAY.getType().equals(payType)){
            /**
             * 选择支付宝支付
             */
            try{
                String form =  AlipayUtils.postPayAction(outTradeNo,order.getPrice(),order.getCommodityInfo(),order.getReturnUrl(),url + Constants.ALI_NOTIFY_URL);
                //正在支付
                order.setStatus(OrderStatus.PAYING.getStatus());
                response.setContentType("text/html;charset=utf-8");
                writer = response.getWriter();
                writer.write(form);
                writer.flush();
                writer.close();
                return;
            }catch (Exception e){
                logger.error(ErrorCode.ALIPAY_ORDER_FAIL.getDescription() + ":{}",e.getMessage());
                result = ResultUtils.parseFailure(ErrorCode.ALIPAY_ORDER_FAIL.toString(), ErrorCode.ALIPAY_ORDER_FAIL.getDescription());
                writeJsonResponse(result,response);
                e.printStackTrace();
                return;
            }finally {
                order.setPayType(PayType.ALIPAY.getType());
                payService.updateOrder(order);
            }
        }else if(PayType.WEIXIN.getType().equals(payType)) {
            /**
             * 选择微信支付
             */
            Map<String, String> parameters = new HashMap<String, String>();
            parameters.put("out_trade_no", outTradeNo);
            parameters.put("body", order.getCommodityInfo());
            parameters.put("attach",order.getPayUserInfo());
            parameters.put("total_fee", String.valueOf((int) 100 * order.getPrice()));
            parameters.put("trade_type", "MWEB");
            parameters.put("spbill_create_ip",WebUtils.getClientIp(request));
            Map<String,String> sceneInfo = new HashMap<String ,String>();
            sceneInfo.put("type","Wap");
            sceneInfo.put("wap_url","https://www.baidu.com");
            sceneInfo.put("wap_name","测试");
            parameters.put("h5_info",GsonUtils.toJson(sceneInfo));
            try{
                Map<String,String> res = WeixinPayUtils.postPayAction(parameters,url + Constants.WX_NOTIFY_URL);
                if(res != null ){
                    /**
                     * 正常下单
                     */
                    if("SUCCESS".equals(res.get("return_code"))){
                        if("SUCCESS".equals(res.get("result_code"))){
                            /**
                             * 预支付交易会话标识
                             */
                            String  prepay_id = res.get("prepay_id");
                            String  mweb_url = res.get("mweb_url");
                            String  returnUrl = order.getReturnUrl();
                            order.setStatus(OrderStatus.PAYING.getStatus());
                            order.setPayOrderNo(prepay_id);
                            response.sendRedirect(mweb_url + "&redirect_url=" + WebUtils.encodeURI(returnUrl));
                        }else{
                            /**
                             * 获取微信下单错误描述
                             */
                            order.setStatus(OrderStatus.PAY_FAILED.getStatus());
                            result = ResultUtils.parseFailure(res.get("err_code"),res.get("err_code_des"));
                            writeJsonResponse(result,response);
                            return;
                        }
                    }else{
                        result = ResultUtils.parseFailure(ErrorCode.COMMUNICATION_FAIL.toString(),ErrorCode.COMMUNICATION_FAIL.getDescription());
                        writeJsonResponse(result,response);
                    }
                }
            }catch(Exception e){
                logger.error(ErrorCode.WEIXIN_ORDER_FAIL.getDescription() + ":{}",e.getMessage());
                result = ResultUtils.parseFailure(ErrorCode.WEIXIN_ORDER_FAIL.toString(), ErrorCode.WEIXIN_ORDER_FAIL.getDescription());
                writeJsonResponse(result,response);
                e.printStackTrace();
                return;
            }finally {
                order.setPayType(PayType.WEIXIN.getType());
                payService.updateOrder(order);
            }
        }
    }


    /**
     * 支付宝异步通知
     * @param request
     * @param response
     */
    @RequestMapping(value="alipayNotify")
    public void alipayNotify(HttpServletRequest request,HttpServletResponse response){

            /**
             *
             * 获取异步通知结果
             */
            Map<String,String>  parameters = WebUtils.getRequestParameter(request);
            /**
             * 重新打包数据发给用户
             */
            Map<String,String> pack = new HashMap<String,String>();

            /**
             * 签名状态
             */
            boolean verified = false;
            Order order = null;
            String outTradeNo =  parameters.get("out_trade_no");
            String tradeStatus = parameters.get("trade_status");
            String trade_no = parameters.get("trade_no");
            order = payService.findOrderByOrderNo(outTradeNo);
            if(order == null){
                /**
                 * 不存在的订单
                 */
                return;
            }
            try {
                 verified = AlipayUtils.signVerified(parameters);
            }catch(Exception e){
                /**
                 * 验证签名异常
                 */
                logger.error("验证签名异常:{}",e.getMessage());
            }

            pack.put("code","SUCCESS");
            pack.put("total_fee", ""+MathUtil.roundScale(parameters.get("total_amount"),2).multiply(new BigDecimal("100")).intValue());
            pack.put("subject",parameters.get("subject"));
            pack.put("body",parameters.get("body"));
            pack.put("out_trade_no",outTradeNo);
            pack.put("trade_no",trade_no);
            pack.put("attach",order.getPayUserInfo());
            /**
             * 校验签名成功
             */
            if(verified){
                if(tradeStatus.equals("TRADE_SUCCESS")){
                    pack.put("result_code","SUCCESS");
                    pack.put("message","支付成功");
                }else if(tradeStatus.equals("TRADE_FINISHED")){
                    pack.put("result_code","SUCCESS");
                    pack.put("message","支付成功");

                }else if(tradeStatus.equals("TRADE_CLOSED")){
                    pack.put("result_code","CLOSED");
                    pack.put("message","订单关闭");
                }else if(tradeStatus.equals("WAIT_BUYER_PAY")){
                    pack.put("result_code","WAITING");
                    pack.put("message","等待用户支付");
                }
            }else{
                pack.put("result_code","FAIL");
                pack.put("message","签名错误");
            }
            pack.put("signature", WebUtils.signature(pack,order.getAppSecret(),SignType.md5));
            /**
             * 平台回调用户的接口，商户平台必须正确响应支付回调
             */
            String result = HttpClientUtils.postFormRequest(order.getCallbackUrl(),Constants.CHARSET,pack);
            /**
             * 通信异常
             */
            if(result == null){
                logger.warn("Cannot connect to notify_url",order.getCallbackUrl());
                writeStatus("failure",response);
            }else if("SUCCESS".equalsIgnoreCase(result)){
                /**
                 * 支付成功
                 */
                if(tradeStatus.equals("TRADE_SUCCESS") || tradeStatus.equals("TRADE_FINISHED")){
                    /**
                     * 支付成功状态
                     */
                    if(order != null
                            && !OrderStatus.PAYED.getStatus().equals(order.getStatus())
                            && !OrderStatus.FINISHED.getStatus().equals(order.getStatus())){
                        //设置为成功
                        if(tradeStatus.equals("TRADE_SUCCESS")){
                            order.setStatus(OrderStatus.PAYED.getStatus());
                        }else{
                            order.setStatus(OrderStatus.FINISHED.getStatus());
                        }
                        order.setPayTime(DateUtil.format(new Date(),DateUtil.YYYY_MM_DD$HH_mm_ss$SSS));
                        order.setPayOrderNo(trade_no);
                        App app = new App();
                        app.setId(order.getAppId());
                        app.setProfit(order.getPrice());
                        payService.updateOrder(order);
                        payService.updateProfit(app);
                    }
                }
                else if(tradeStatus.equals("TRADE_CLOSED")){
                    /**
                     * 未付款交易超时关闭，或支付完成后全额退款
                     */
                    if(order != null && !OrderStatus.OVERDUE.equals(order.getStatus())){
                        order.setStatus(OrderStatus.OVERDUE.getStatus());
                        order.setPayOrderNo(trade_no);
                        payService.updateOrder(order);
                    }
                }else{
                    if(order != null && !OrderStatus.PAY_FAILED.equals(order.getStatus())){
                        order.setStatus(OrderStatus.OVERDUE.getStatus());
                        order.setPayOrderNo(trade_no);
                        payService.updateOrder(order);
                    }
                }
                writeStatus("success",response);
            }else{
                writeStatus("failure",response);
            }

    }



    /**
     * 写状态
     * @param status
     * @param response
     */
    private void writeStatus(String status,HttpServletResponse response){
        try{
            writer = response.getWriter();
            writer.write(status);
            writer.flush();
            writer.close();
        }catch(Exception e1){
            e1.printStackTrace();
        }
    }



    /**
     * 微信异步通知
     * @param request
     * @param response
     */
    @RequestMapping(value="weixinNotify")
    public void weixinNotify(HttpServletRequest request,HttpServletResponse response){

       try{
           String contentType = request.getContentType().toUpperCase();
           if(contentType.contains("text/xml")){
               InputStream is =  request.getInputStream();
               String xml = WebUtils.parseStreamToStr(is);
               Map<String,String> result = WXPayUtil.xmlToMap(xml);
               String return_code = result.get("return_code");
               String outTradeNo =  result.get("out_trade_no");
               String result_code = result.get("result_code");
               String trade_no = result.get("transaction_id");
               Order order = null;
               /**
                * 重新打包数据发给用户
                */
               Map<String,String> pack = new HashMap<String,String>();
               /**
                * 签名状态
                */
               boolean verified = false;
               if("SUCCESS".equals(return_code)){
                    pack.put("code","SUCCESS");
                   /**
                    * 验证签名
                    */
                   verified = WXPayUtil.isSignatureValid(result,Constants.WX_KEY);
                   order = payService.findOrderByOrderNo(outTradeNo);
                   if(order == null){
                       /**
                        * 不存在的订单
                        */
                       return;
                   }
                   pack.put("out_trade_no",outTradeNo);
                   pack.put("trade_no",trade_no);
                   pack.put("body",result.get("attach"));
                   pack.put("total_fee", result.get("total_fee"));
                   if(verified){
                        if("SUCCESS".equals(result_code)){
                            pack.put("result_code","SUCCESS");
                            pack.put("message","支付成功");

                        }else{
                            pack.put("result_code",result.get("err_code"));
                            pack.put("message",result.get("err_code_des"));
                        }
                   }else{
                       pack.put("result_code","FAIL");
                       pack.put("message","签名错误");
                   }
               }else{
                   //通信错误
                   pack.put("code","FAIL");
               }
               pack.put("attach",order.getPayUserInfo());
               pack.put("signature", WebUtils.signature(pack,order.getAppSecret(),SignType.md5));
                /**
                 * 平台回调用户的接口，商户平台必须正确响应支付回调
                 * */
               String res = HttpClientUtils.postFormRequest(order.getCallbackUrl(),Constants.CHARSET,pack);
               if(res == null){
                   logger.warn("Cannot connect to notify_url",order.getCallbackUrl());
                   writeStatus("FAIL",response);
               }else if("SUCCESS".equalsIgnoreCase(res)){
                   /**
                    * 不是支付成功状态
                    */
                   if(order != null
                           && !OrderStatus.PAYED.getStatus().equals(order.getStatus())
                           && !OrderStatus.FINISHED.getStatus().equals(order.getStatus())){
                       //设置为成功
                       order.setStatus(OrderStatus.PAYED.getStatus());
                       order.setPayTime(DateUtil.format(new Date(),DateUtil.YYYY_MM_DD$HH_mm_ss$SSS));
                       order.setPayOrderNo(trade_no);
                       App app = new App();
                       app.setId(order.getAppId());
                       app.setProfit(order.getPrice());
                       payService.updateOrder(order);
                       payService.updateProfit(app);
                   }
                   writeStatus("SUCCESS",response);
               }else{
                   writeStatus("FAIL",response);
               }
           }
       }catch (Exception e){
           e.printStackTrace();
       }

    }

    /**
     * 发起支付的页面
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping(value="payUrl",method = RequestMethod.GET)
    public void toPay(HttpServletRequest request, HttpServletResponse response, Model model)throws  IOException,ServletException{
        String orderNo = request.getParameter("orderNo");
        Order order = payService.findOrderByOrderNo(orderNo);
        if(order == null){
            response.setContentType("text/html;charset=utf-8");
            writer = response.getWriter();
            writer.write(ErrorCode.INVALID_PAY_URL.getDescription());
            writer.flush();
        }else{
            Integer status = order.getStatus();
            if(OrderStatus.WAITING.getStatus().equals(status)){
                String beginTime =  order.getBeginTime();
                Date created = DateUtil.parse(beginTime,DateUtil.YYYY_MM_DD$HH_mm_ss$SSS);
                Date now = new Date();
                /**
                 * 超过3分钟未发起支付链接实效
                 */
                if(now.getTime() - created.getTime() > 180000 ){
                    /**
                     * 更新状态为过期未支付
                     */
                    order.setStatus(OrderStatus.OVERDUE.getStatus());
                    payService.updateOrder(order);
                    response.setContentType("text/html;charset=utf-8");
                    writer = response.getWriter();
                    writer.write(ErrorCode.PAY_URL_OVERDUE.getDescription());
                    writer.flush();

                }else{
                    /**
                     * 跳转到支付页面
                     */
                    request.setAttribute("orderNo",orderNo);
                    request.setAttribute("title",request.getParameter("title"));
                    request.setAttribute("price",request.getParameter("price"));
                    request.getRequestDispatcher("/WEB-INF/pages/index.jsp").forward(request,response);
                }
            }else{
                /**
                 * 已经处理过的订单
                 */
                response.setContentType("text/html;charset=utf-8");
                writer = response.getWriter();
                writer.write(ErrorCode.INVALID_PAY_URL.getDescription());
                writer.flush();
            }

        }

    }

}
